package com.yummy.cloud.gateway.manage.service;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.yummy.cloud.gateway.manage.dao.mapper.LoadBalancerConfigMapper;
import com.yummy.cloud.gateway.manage.dao.model.LoadBalancerConfig;
import com.yummy.cloud.gateway.manage.dao.model.LoadBalancerConfigExample;
import com.yummy.cloud.gateway.manage.dao.model.LoadBalancerConfigExample.Criteria;
import com.yummy.cloud.gateway.manage.dto.LoadBalancerConfigQuery;
import com.yummy.convention.exception.BusinessException;
import com.yummy.convention.page.Pagination;

@Service
public class LoadBalancerConfigService {
	
	@Autowired
	private LoadBalancerConfigMapper loadBalancerConfigMapper;

	public Pagination<LoadBalancerConfig> getConfigs(LoadBalancerConfigQuery query) {
		List<LoadBalancerConfig> list = getFromDB(query);
		if(list == null) {
			return Pagination.empty(0);
		}
		long total = ((Page<LoadBalancerConfig>)list).getTotal();
		return Pagination.create(total, list);
	}

	private List<LoadBalancerConfig> getFromDB(LoadBalancerConfigQuery query) {
		LoadBalancerConfigExample example = new LoadBalancerConfigExample();
		Criteria criteria = example.createCriteria();
		if(!StringUtils.isEmpty(query.getServiceId())) {
			criteria.andIdLike(query.getServiceId());
		}
		PageHelper.startPage(query.getPageNum(),query.getPageSize());
		return loadBalancerConfigMapper.selectByExample(example);
	}

	public LoadBalancerConfig getConfig(String serviceId) {
		return loadBalancerConfigMapper.selectByPrimaryKey(serviceId);
	}

	public Boolean saveConfig(LoadBalancerConfig config) {
		int row = loadBalancerConfigMapper.updateByPrimaryKey(config);
		if(row <= 0) {
			loadBalancerConfigMapper.insert(config);
		}
		return true;
	}

	public Boolean createConfig(LoadBalancerConfig config) {
		if(exist(config.getId())) {
			throw new BusinessException("已经有id="+config.getId()+"的配置");
		}
		loadBalancerConfigMapper.insert(config);
		return true;
	}

	private boolean exist(String id) {
		LoadBalancerConfig exist = getConfig(id);
		if(exist == null) {
			return false;
		}
		return true;
	}

	public Boolean updateConfig(LoadBalancerConfig config) {
		int row = loadBalancerConfigMapper.updateByPrimaryKey(config);
		if(row <= 0) {
			throw new BusinessException("配置不存在id="+config.getId());
		}
		return true;
	}

	public Boolean deleteConfig(String serviceId) {
		int row = loadBalancerConfigMapper.deleteByPrimaryKey(serviceId);
		if(row <= 0) {
			throw new BusinessException("配置不存在id="+serviceId);
		}
		return true;
	}

}
